const Department = require('../models/Department');
const User = require('../models/User');
const { Op } = require('sequelize');

// 创建部门
exports.createDepartment = async (req, res) => {
  try {
    // 仅管理员可创建部门
    if (req.user.role !== 'admin') {
      return res.status(403).json({
        success: false,
        message: '权限不足，仅管理员可创建部门'
      });
    }

    const { name, description, managerId } = req.body;

    // 验证部门名称是否已存在
    const existingDepartment = await Department.findOne({ where: { name } });
    if (existingDepartment) {
      return res.status(400).json({
        success: false,
        message: '部门名称已存在'
      });
    }

    // 验证部门经理是否存在
    if (managerId) {
      const manager = await User.findByPk(managerId);
      if (!manager) {
        return res.status(404).json({
          success: false,
          message: '指定的部门经理不存在'
        });
      }
    }

    // 创建部门
    const department = await Department.create({
      name,
      description,
      managerId: managerId || null
    });

    return res.status(201).json({
      success: true,
      message: '部门创建成功',
      data: department
    });
  } catch (error) {
    console.error('创建部门失败:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误，创建部门失败',
      error: error.message
    });
  }
};

// 获取所有部门
exports.getAllDepartments = async (req, res) => {
  try {
    const { page = 1, limit = 10, status, search } = req.query;
    const offset = (page - 1) * limit;
    const whereClause = {};

    // 筛选条件
    if (status) whereClause.status = status;
    if (search) {
      whereClause.name = { [Op.like]: `%${search}%` };
    }

    const { count, rows: departments } = await Department.findAndCountAll({
      where: whereClause,
      include: [
        {
          model: User,
          as: 'Manager',
          attributes: ['id', 'name', 'email']
        }
      ],
      order: [['name', 'ASC']],
      limit: parseInt(limit),
      offset: parseInt(offset)
    });

    return res.status(200).json({
      success: true,
      total: count,
      page: parseInt(page),
      limit: parseInt(limit),
      data: departments
    });
  } catch (error) {
    console.error('获取部门列表失败:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误，获取部门列表失败',
      error: error.message
    });
  }
};

// 获取单个部门详情
exports.getDepartmentById = async (req, res) => {
  try {
    const { id } = req.params;

    const department = await Department.findByPk(id, {
      include: [
        {
          model: User,
          as: 'Manager',
          attributes: ['id', 'name', 'email']
        },
        {
          model: User,
          as: 'Users',
          attributes: ['id', 'name', 'email', 'role'],
          through: { attributes: [] }
        }
      ]
    });

    if (!department) {
      return res.status(404).json({
        success: false,
        message: '部门不存在'
      });
    }

    return res.status(200).json({
      success: true,
      data: department
    });
  } catch (error) {
    console.error('获取部门详情失败:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误，获取部门详情失败',
      error: error.message
    });
  }
};

// 更新部门信息
exports.updateDepartment = async (req, res) => {
  try {
    // 仅管理员可更新部门
    if (req.user.role !== 'admin') {
      return res.status(403).json({
        success: false,
        message: '权限不足，仅管理员可更新部门'
      });
    }

    const { id } = req.params;
    const { name, description, managerId, status } = req.body;

    const department = await Department.findByPk(id);
    if (!department) {
      return res.status(404).json({
        success: false,
        message: '部门不存在'
      });
    }

    // 如果修改了部门名称，检查新名称是否已存在
    if (name && name !== department.name) {
      const existingDepartment = await Department.findOne({ where: { name } });
      if (existingDepartment) {
        return res.status(400).json({
          success: false,
          message: '部门名称已存在'
        });
      }
    }

    // 如果指定了部门经理，验证经理是否存在
    if (managerId) {
      const manager = await User.findByPk(managerId);
      if (!manager) {
        return res.status(404).json({
          success: false,
          message: '指定的部门经理不存在'
        });
      }
    }

    // 更新部门信息
    await department.update({
      name: name || department.name,
      description: description || department.description,
      managerId: managerId !== undefined ? managerId : department.managerId,
      status: status || department.status
    });

    return res.status(200).json({
      success: true,
      message: '部门更新成功',
      data: department
    });
  } catch (error) {
    console.error('更新部门失败:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误，更新部门失败',
      error: error.message
    });
  }
};

// 删除部门
exports.deleteDepartment = async (req, res) => {
  try {
    // 仅管理员可删除部门
    if (req.user.role !== 'admin') {
      return res.status(403).json({
        success: false,
        message: '权限不足，仅管理员可删除部门'
      });
    }

    const { id } = req.params;

    const department = await Department.findByPk(id);
    if (!department) {
      return res.status(404).json({
        success: false,
        message: '部门不存在'
      });
    }

    // 检查部门下是否有关联用户
    const users = await department.getUsers();
    if (users && users.length > 0) {
      return res.status(400).json({
        success: false,
        message: '无法删除部门，该部门下仍有关联用户'
      });
    }

    await department.destroy();

    return res.status(200).json({
      success: true,
      message: '部门删除成功'
    });
  } catch (error) {
    console.error('删除部门失败:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误，删除部门失败',
      error: error.message
    });
  }
};

// 为部门添加用户
exports.addUserToDepartment = async (req, res) => {
  try {
    // 仅管理员可操作
    if (req.user.role !== 'admin') {
      return res.status(403).json({
        success: false,
        message: '权限不足，仅管理员可操作'
      });
    }

    const { departmentId } = req.params;
    const { userId } = req.body;

    // 验证部门和用户是否存在
    const department = await Department.findByPk(departmentId);
    const user = await User.findByPk(userId);

    if (!department) {
      return res.status(404).json({
        success: false,
        message: '部门不存在'
      });
    }

    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    // 添加用户到部门
    await department.addUser(user);

    return res.status(200).json({
      success: true,
      message: '用户已成功添加到部门'
    });
  } catch (error) {
    console.error('添加用户到部门失败:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误，添加用户到部门失败',
      error: error.message
    });
  }
};

// 从部门移除用户
exports.removeUserFromDepartment = async (req, res) => {
  try {
    // 仅管理员可操作
    if (req.user.role !== 'admin') {
      return res.status(403).json({
        success: false,
        message: '权限不足，仅管理员可操作'
      });
    }

    const { departmentId, userId } = req.params;

    // 验证部门和用户是否存在
    const department = await Department.findByPk(departmentId);
    const user = await User.findByPk(userId);

    if (!department) {
      return res.status(404).json({
        success: false,
        message: '部门不存在'
      });
    }

    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    // 从部门移除用户
    await department.removeUser(user);

    return res.status(200).json({
      success: true,
      message: '用户已成功从部门移除'
    });
  } catch (error) {
    console.error('从部门移除用户失败:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误，从部门移除用户失败',
      error: error.message
    });
  }
};